package com.haifeng.CRUD.web.servlet;

import com.haifeng.CRUD.domain.User;
import com.haifeng.CRUD.service.impl.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);
        LoginServiceImpl loginService = new LoginServiceImpl();
        User user = loginService.userLogin(loginUser);

        if (user==null){
            //为空，登录失败
            System.out.println("登录失败");
            //跳转到错误界面
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }else {
            System.out.println("登录成功！");
            //查询到值，登录成功，把对象存入session中
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            //请求转发到successServlet
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
